package ro.imc.rest.client.display;

import ro.imc.rest.client.display.util.DialogForm;
import ro.imc.rest.client.display.util.MessageConstants;
import ro.imc.rest.client.display.util.RootPanelDivId;
import ro.imc.rest.client.display.util.RootPanelManager;
import ro.imc.rest.client.services.forserver.RestService;
import ro.imc.rest.client.services.forserver.RestServiceAsync;
import ro.imc.rest.shared.dto.RestLogin;

import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.event.dom.client.ClickEvent;


public class LoginBoxForm extends Composite {

	private static LoginBoxFormUiBinder uiBinder =
		GWT.create(LoginBoxFormUiBinder.class);
	
	private static RestServiceAsync restService = 
		GWT.create(RestService.class);
	
	@UiField PasswordTextBox pwdField;
	@UiField TextBox userField;
	@UiField Button loginBtn;

	interface LoginBoxFormUiBinder extends UiBinder<Widget, LoginBoxForm> {
	}

	public LoginBoxForm() {
		initWidget(uiBinder.createAndBindUi(this));
	}

	@UiHandler("loginBtn")
	void onLoginBtnClick(ClickEvent event) {
		restService.loginToRestApi(userField.getText(), pwdField.getText(), new AsyncCallback<RestLogin>() {
			
			@Override
			public void onSuccess(RestLogin result) {
				RootPanel.get(RootPanelDivId.LOGIN_FORM_ID).clear();
				attachUiAfterLogin(result);
			}
			
			@Override
			public void onFailure(Throwable caught) {
				DialogForm.displayDialog(MessageConstants.LOGIN_ERR_TITLE,
					MessageConstants.getLoginErrHtml(userField.getText()),
					MessageConstants.LOGIN_ERR_TIP);
				
			}
		});
	}
	private void attachUiAfterLogin(RestLogin user) {
		RootPanelManager.attachForm(RootPanelDivId.START_BAR_ID, new StartBarForm(user));
	}
}
